package com.qifei.xmlg_backend.utils.minio;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
@RequiredArgsConstructor
public class MinioUtils {

    private final MinioProps minioProps;
    private final MinioClient minioClient;

    public String upload(MultipartFile file) throws Exception {
        String bucketName = minioProps.getBucketName();

        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = UUID.randomUUID().toString() + ext;

        try (InputStream in = file.getInputStream()) {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName)
                            .object(objectName)
                            .stream(in,file.getSize(),-1)
                            .contentType(file.getContentType())
                            .build()
            );
            return minioProps.getEndpoint() + "/" + bucketName + "/" + objectName;
        }
    }

}
